package com.bjy.qa.agent.tools.script;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bjy.qa.agent.exception.BreakException;
import com.bjy.qa.agent.response.Response;
import com.bjy.qa.agent.tools.EnvCheckTool;
import com.bjy.qa.agent.tools.ProcessCommandTool;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Python 脚本
 */
public class PythonScript implements Script {

    @Override
    public Response run(Response response, Map<String, Object> globalParas, String script) {
        if (StringUtils.isEmpty(EnvCheckTool.pythonCommand)) {
            throw new BreakException("运行自定义 Python 脚本失败。\n" +
                    "1、没安装 python3，请安装\n" +
                    "2、已安装 python3，请打开 application.yml ，将 qap.python.command 对应的内容修改为 python3 的 路径+命令\n" +
                    "3、已安装 python3，也可以在 path 中添加 python3 路径 或 添加 python3 别名");
        }

        File temp = new File("test-output" + File.separator + UUID.randomUUID() + ".py");
        try {
            // 执行脚本
            temp.createNewFile();
            FileWriter fileWriter = new FileWriter(temp);
            fileWriter.write(script);
            fileWriter.close();
            String result = ProcessCommandTool.getProcessLocalCommandStr(
                    String.format(
                            "%s \"%s\" \"%s\" \"%s\"",
                            EnvCheckTool.pythonCommand,
                            temp.getAbsolutePath(),
                            JSON.toJSONString(response, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}).replace("\\", "\\\\").replace("\"","\\\""),
                            JSON.toJSONString(globalParas, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}).replace("\\", "\\\\").replace("\"","\\\"")
                    )
            );
            // 生成返回结果
            Map<String, Object> ret = new HashMap<>();
            ret.put("ret", result);
            String resultJson = JSON.toJSONString(ret, new SerializerFeature[]{SerializerFeature.WriteMapNullValue});
            Response responseReturn = new Response(resultJson, null);

            return responseReturn;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }  finally {
            temp.delete();
        }
    }

}
